//
//  SettingViewController.m
//  VICKY ZONE
//
//  Created by sunx on 15/3/24.
//  Copyright (c) 2015年 sunx. All rights reserved.
//
#define SERVER @"http://samoyun.com/controller/blogController.php"
#define MANAGER @"http://samoyun.com/controller/mainController.php"

#import "SettingViewController.h"
#import "LoginViewController.h"
#import "HeadImageCell.h"
#import "ClearCell.h"
#import "BlogViewController.h"
#import "MyViewController.h"
#import "MoodCell.h"
#import "MainViewController.h"
#import "NSURLSession+KKAddition.h"
#import "GDataXMLNode.h"
#import "SVProgressHUD.h"
#import "UsernameCell.h"
#import "MenuButtonCell.h"

@interface MainViewController ()
@property(nonatomic,strong) NSString *username;
@property(nonatomic,strong) MoodCell *moodcell;
@property(nonatomic,strong) NSString *mood;
@property(nonatomic,strong) HeadImageCell *headcell;
@property(strong, nonatomic) UIImagePickerController *imagePicker;
@end

@implementation MainViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    /*
     if debug
     */
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    [userDefault setInteger:0 forKey:app_Version];
    [userDefault setObject:@"" forKey:@"username"];
    NSLog(@"viewDidLoad");
    
}
- (void)viewWillAppear:(BOOL)animated {
    NSLog(@"viewWillAppear");
    
    if([self isLogin]) {
        self.tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
        self.tableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        self.tableView.scrollEnabled = NO;
        self.view.backgroundColor = [UIColor grayColor];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mainbac"]];
        imageView.frame = self.view.frame;
        [self.view addSubview:imageView];
        [self.view sendSubviewToBack:imageView];
        
        //NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        //self.username = (NSString *)[userDefault objectForKey:@"username"];
        
        NSLog(@"%@",NSHomeDirectory());
        
        ClearCell *clear1 = [[ClearCell alloc] initWithHeight:0.06];
        
        //head cell
        NSString *head = [[NSString alloc] initWithFormat:@"http://www.samoyun.com/user/%@/imgs/_head.png",self.username];
        NSLog(@"%@",head);
        
        self.headcell = [[HeadImageCell alloc] initWithImageURL:head];
        
        __block MainViewController *blockself = self;
        self.headcell.actionBlock = ^{[blockself makeActionSheetAppear];};
        
        ClearCell *clear2 = [[ClearCell alloc] initWithHeight:0.02];
        
        UsernameCell *userNameCell = [[UsernameCell alloc] init];
        
        ClearCell *clear3 = [[ClearCell alloc] initWithHeight:0.06];
        
        //mood cell
        self.moodcell = [[MoodCell alloc] initWithString:@""];
        
        ClearCell *clear4 = [[ClearCell alloc] initWithHeight:0.02];
        
        
        MenuButtonCell *blogButtonCell = [MenuButtonCell buttonWithTitle:@"MY BLOG" andAction:^{
            BlogViewController *blog = [[BlogViewController alloc] init];
            [self.navigationController pushViewController:blog animated:YES];
        }];
        
        ClearCell *clear5 = [[ClearCell alloc] initWithHeight:0.015];
        
        
        MenuButtonCell *axisButtonCell = [MenuButtonCell buttonWithTitle:@"TIMELINE" andAction:^{
            MyViewController *axis = [[MyViewController alloc] init];
            [self.navigationController pushViewController:axis animated:YES];
        }];
        
        ClearCell *clear6 = [[ClearCell alloc] initWithHeight:0.015];
        
        
        MenuButtonCell *settingButtonCell = [MenuButtonCell buttonWithTitle:@"SETTING" andAction:^{
            SettingViewController *setting = [[SettingViewController alloc] init];
            [self.navigationController pushViewController:setting animated:YES];
        }];
        
        
        
        OrganicSection *mainSection = [OrganicSection sectionWithCells:@[clear1,self.headcell,clear2,userNameCell,clear3,self.moodcell,clear4,blogButtonCell,clear5,axisButtonCell,clear6,settingButtonCell]];
        self.sections = @[mainSection];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    NSLog(@"viewDidAppear");
    //xml解析
        if([self isLogin]) {
            [NSURLSession GET:SERVER pararms:@{@"user":self.username,@"type":@"others"} completed:^(NSData *data) {
                
                GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];
                GDataXMLElement *element = [document rootElement];
                self.mood = [[element children][2] stringValue];
                
                [self performSelectorOnMainThread:@selector(updateMood) withObject:nil waitUntilDone:YES];
                
            } failed:^(NSError *error) {
                if(error) {
                    NSLog(@"%@",error);
                }
            }];
            NSLog(@"已经登录");
        }else {
            NSLog(@"未登录");
            [self jumpToLoginPage];
        }
    
}

- (BOOL)isLogin {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    self.username = (NSString *)[userDefault objectForKey:@"username"];
    if([self.username isEqualToString:@""] || self.username == nil ) {
        //NSLog(@"未登录");
        //[self jumpToLoginPage];
        return NO;
    }else {
        NSLog(@"user:%@",self.username);
        return YES;
    }
}
- (void)jumpToLoginPage {
    UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ;
    //NSLog(@"..");

    [self presentViewController:[main instantiateViewControllerWithIdentifier:@"login"] animated:YES completion:^{
        NSLog(@"jump to login page");
    }];
    //NSLog(@"0 0");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Action Sheet
- (void)makeActionSheetAppear {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Edit Avatar"
                                                             delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
                                                    otherButtonTitles:@"Take Photo", @"Choose From Library", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"actionSheet");
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0) {
        [self pushTakePhotoScreenInDelegate];
    }
    else if (buttonIndex == 1) {
        [self pushChoosePhotoScreenInDelegate];
    }
}

-(void)pushTakePhotoScreenInDelegate
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.delegate = self;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

-(void)pushChoosePhotoScreenInDelegate
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.delegate = self;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [SVProgressHUD show];
    self.headcell.imageView.image = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSLog(@"%@",timeString);
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filename = @"_head.png";
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent: filename];
    [self removeImage];
    
    // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(self.headcell.imageView.image)writeToFile: filePath    atomically:YES];
    // 保存成功会返回YES
    if(result) {
        [NSURLSession Upload:filePath user:self.username type:@"header" filename:filename progress:^(CGFloat progress) {
            
        } completed:^(NSData *data){
            [self performSelectorOnMainThread:@selector(HUDDissmiss) withObject:self waitUntilDone:YES];
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        } failed:^(NSError *error) {
            if(error) {
                NSLog(@"%@",error);
                [SVProgressHUD dismiss];
            }
        }];
    }
}
#pragma mark - select motheds
- (void)HUDDissmiss {
    [SVProgressHUD dismiss];
}

- (void)updateMood {
    self.moodcell.textView.text = self.mood;
}

//上传头像之前删除之前的头像
- (void)removeImage {
    NSString *imageDir = [NSString stringWithFormat:@"%@/Documents/_head.png", NSHomeDirectory()];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:imageDir error:nil];
}
@end
